/*
 * =====================================================================================
 *
 *       Filename:  NameService.h
 *
 *    Description:  class that support NetBIOS protocol
 *
 *        Version:  1.0
 *        Created:  2012年02月14日 15时57分50秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Regan (), lcqhigh@gmail.com
 *        Company:  
 *
 * =====================================================================================
 */
#ifndef NAME_SERVICE
#define NAME_SERVICE

#include	<vector>
#include "NbtUtil.h"

class NameService 
{
    public:
        NameService();
        
        //TODO:return the errcode indicating which is wrong
        //use broadcast to register name can generate broadcast storm
        bool registerName(string name, const struct in_addr *ip);
        //query who has the name 
        bool queryName(string name, struct in_addr* ip);

        bool releaseName(string name);
        //
        void runAsDemon();
        //
        void run();
        
    private:
        std::vector<name_t> names_;
        std::vector<string> registerednames_;
        struct in_addr myip_;
        struct in_addr bcastIp_;
        string myname_;
        socket_t sockfd_;
        static uint32_t myTTL_;
        uint16_t nameTransId_;

        char inBuffer_[1024];
        char outBuffer_[1024];
        //
        void replyRegRequest(char *inbuf, char *outbuf, const struct in_addr lastip);
        //
        void replyRegDemand(char *inbuf, char *outbuf, const struct in_addr lastip);
        //
        void replyNameQuery(char *inbuf, char *outbuf, const struct in_addr lastip);
        //
        void reply(char *inbuf, char *outbuf, const struct in_addr lastip);
        //
        void replyReleaseName(const char *inbuf, const struct in_addr lastip);
        //find the namestr and return the index
        int findName(string namestr);
        //
        int addName(string namestr, struct in_addr ip);
};

#endif
